﻿(function(){

        window.H5lock = function(obj){
            this.chooseType = Number(window.localStorage.getItem('chooseType')) || obj.chooseType;
            this.linwidth = obj.linwidth
            this.successcolor = obj.successcolor
            this.successbgcolor = obj.successbgcolor
            this.wariningcolor = obj.wariningcolor
            this.wariningbgcolor = obj.wariningbgcolor
            this.initcolor = obj.initcolor
            this.inr = obj.inr
            this.outr = obj.outr
            this.initr = obj.initr
        };
 
 
        H5lock.prototype.drawCle = function(x, y,) { // 初始化解锁密码面板
            this.drawStatusPoint(this.successcolor)
            this.ctx.fillStyle = this.initcolor;
            this.ctx.beginPath();
            this.ctx.arc(x, y, this.initr * window.devicePixelRatio, 0, Math.PI * 2, true);
            this.ctx.closePath();
            this.ctx.fill();
        }
        H5lock.prototype.drawPoint = function(color,colorout) { // 初始化外环
            for (var i = 0 ; i < this.lastPoint.length ; i++) {
                this.ctx.fillStyle = colorout;
                this.ctx.beginPath();
                this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.outr * window.devicePixelRatio, 0, Math.PI * 2, false);
                this.ctx.closePath();
                this.ctx.fill();
                this.ctx.fillStyle = color;
                this.ctx.beginPath();
                this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.inr * window.devicePixelRatio, 0, Math.PI * 2, true);
                this.ctx.closePath();
                this.ctx.fill();
                }
        }
        H5lock.prototype.drawStatusPoint = function(type) { // 初始化状态线条
            for (var i = 0 ; i < this.lastPoint.length ; i++) {
                this.ctx.strokeStyle = type;
                this.ctx.beginPath();
                this.ctx.closePath();
                // 这是内环外边框
                // this.ctx.arc(this.lastPoint[i].x - 10, this.lastPoint[i].y, 0, Math.PI * 2, true);
                // this.ctx.stroke();
            }
        }
        H5lock.prototype.drawLine = function(po,color) {// 解锁轨迹
            this.ctx.beginPath();
            this.ctx.lineWidth = this.linwidth * window.devicePixelRatio;
            this.ctx.strokeStyle = color
            this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);
            for (var i = 1 ; i < this.lastPoint.length ; i++) {
                this.ctx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
            }
            this.ctx.lineTo(po.x, po.y);
            this.ctx.stroke();
            this.ctx.closePath();
 
        }
        
        H5lock.prototype.createCircle = function() {// 创建解锁点的坐标，根据canvas的大小来平均分配半径
            var n = this.chooseType;
            var count = 0;
            this.r = this.ctx.canvas.width / (2 + 7.5 * n);// 公式计算
            var r = this.r;
            for (var i = 0 ; i < n ; i++) {
                for (var j = 0 ; j < n ; j++) {
                    count++;
                    var obj = {
                        x: j * 8 * r + 4 * r,
                        y: i * 8 * r + 4 * r,
                        index: count
                    };
                    this.arr.push(obj);
                    this.restPoint.push(obj);
                }
            }
            this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
            for (var i = 0 ; i < this.arr.length ; i++) {
                this.drawCle(this.arr[i].x, this.arr[i].y);
            }
            //return arr;
        }
        H5lock.prototype.getPosition = function(e) {// 获取touch点相对于canvas的坐标
            var rect = e.currentTarget.getBoundingClientRect();
            var po = {
                x: (e.touches[0].clientX - rect.left) * window.devicePixelRatio,
                y: (e.touches[0].clientY - rect.top) * window.devicePixelRatio 
              };
            return po;
        }
        H5lock.prototype.update = function(po) {// 核心变换方法在touchmove时候调用
    
            this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);

            for (var i = 0 ; i < this.arr.length ; i++) { // 每帧先把面板画出来
                this.drawCle(this.arr[i].x, this.arr[i].y);
            }

            this.drawPoint(this.successcolor,this.successbgcolor);// 每帧画轨迹
            this.drawLine(po ,this.successcolor);// 每帧画圆心

            for (var i = 0 ; i < this.restPoint.length ; i++) {
                if (Math.abs(po.x - this.restPoint[i].x) < this.r && Math.abs(po.y - this.restPoint[i].y) < this.r) {
                    // this.drawPoint(this.restPoint[i].x, this.restPoint[i].y);
                    this.lastPoint.push(this.restPoint[i]);
                    this.restPoint.splice(i, 1);
                    break;
                }
            }
        }
        H5lock.prototype.checkPass = function(psw1, psw2) {// 检测密码
            var p1 = '',
            p2 = '';
		
            for (var i = 0 ; i < psw1.length ; i++) {
                p1 += psw1[i].index + psw1[i].index;
            }
            for (var i = 0 ; i < psw2.length ; i++) {
                p2 += psw2[i].index + psw2[i].index;
            }
            return p1 === p2;
        }
        H5lock.prototype.storePass = function(psw) {// touchend结束之后对密码和状态的处理
            console.log(psw)
            if (this.pswObj.step == 1) {
                if (this.checkPass(this.pswObj.fpassword, psw)) {
                    this.pswObj.step = 2;
                    this.pswObj.spassword = psw;
                    document.getElementById('title').innerHTML = '密码设置成功';
                    this.drawStatusPoint('red');
                    window.localStorage.setItem('passwordxx', JSON.stringify(this.pswObj.spassword));
                    window.localStorage.setItem('chooseType', this.chooseType);
                    window.localStorage.setItem('step', 2);
                    document.getElementById('title').innerHTML = '请输入手势密码';
                } else {
                    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
                    for (var i = 0 ; i < this.arr.length ; i++) { // 每帧先把面板画出来
                        this.drawCle(this.arr[i].x, this.arr[i].y);
                    }
                    document.getElementById('title').innerHTML = '两次不一致，重新输入';
                    // this.drawStatusPoint('#FF574D');
                    this.drawPoint(this.wariningcolor,this.wariningbgcolor)
                    this.drawLine( this.lastPoint,this.wariningcolor);// 每帧画圆心

                    delete this.pswObj.step;
                }
            } else if (this.pswObj.step == 2) {
                if (this.checkPass(this.pswObj.spassword, psw)) {
                    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
                    for (var i = 0 ; i < this.arr.length ; i++) { // 每帧先把面板画出来
                        this.drawCle(this.arr[i].x, this.arr[i].y);
                    }
                    this.drawPoint(this.successcolor,this.successbgcolor)
                    this.drawLine( this.lastPoint,this.successcolor);// 每帧画圆心
                    document.getElementById('title').innerHTML = '解锁成功';
                    setTimeout(() => {
                        document.getElementById('goon').click()
                    }, 500);
                } else {
                    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
                    for (var i = 0 ; i < this.arr.length ; i++) { // 每帧先把面板画出来
                        this.drawCle(this.arr[i].x, this.arr[i].y);
                    }
                    this.drawPoint(this.wariningcolor,this.wariningbgcolor)
                    this.drawLine( this.lastPoint,this.wariningcolor);// 每帧画圆心
                    document.getElementById('title').innerHTML = '解锁失败,请重新尝试';
                }
            } else {
                if(psw.length < 4) {
                    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
                    for (var i = 0 ; i < this.arr.length ; i++) { // 每帧先把面板画出来
                        this.drawCle(this.arr[i].x, this.arr[i].y);
                    }
                    this.drawPoint(this.wariningcolor,this.wariningbgcolor)
                    this.drawLine( this.lastPoint,this.wariningcolor);// 每帧画圆心
                    document.getElementById('title').innerHTML = '密码长度不够，请重新输入';
                    return;
                }
                this.pswObj.step = 1;
                this.pswObj.fpassword = psw;
                document.getElementById('title').innerHTML = '再次输入';
            }
 
        }
        H5lock.prototype.makeState = function() {
        }
        H5lock.prototype.setChooseType = function(type){
            chooseType = type;
            init();
        }
        H5lock.prototype.updatePassword = function(){
            window.localStorage.removeItem('passwordxx');
            window.localStorage.removeItem('chooseType');
            window.localStorage.removeItem('step');
            this.pswObj = {};
            document.getElementById('title').innerHTML = '为了保护您的隐私，请设置登录手势密码吧！';
            this.reset();
        }
        H5lock.prototype.initDom = function(){
            var wrap = document.createElement('div');
            if(window.localStorage.getItem('step') !== "2") {
            var str = '<div id="title">为了保护您的隐私，请设置登录手势密码吧！</div>'+
                      '<canvas id="canvas"style="display: inline-block;"></canvas>'+
                      '<div class="bottomtext">至少连接4个点</div>';
            wrap.setAttribute('style','position: absolute; left:0;right:0;');
            wrap.setAttribute('class','gesturepassword');
            wrap.innerHTML = str;
            document.body.appendChild(wrap);
            } else {
            var str = '<div id="title">请输入手势密码</div>'+
                    '<canvas id="canvas" style="display: inline-block;"></canvas>'+
                    '<div class="bottomtext">至少连接4个点</div>';
            wrap.setAttribute('style','position: absolute; left:0;right:0;');
            wrap.setAttribute('class','gesturepassword');
            wrap.innerHTML = str;
            document.body.appendChild(wrap);
            }
            var canvas=document.getElementById('canvas');    
            canvas.width=canvas.clientWidth*window.devicePixelRatio;
            canvas.height=canvas.clientHeight*window.devicePixelRatio;
        } 

        H5lock.prototype.init = function() {
            this.initDom();
            this.pswObj = window.localStorage.getItem('passwordxx') ? {
                step: 2,
                spassword: JSON.parse(window.localStorage.getItem('passwordxx'))
            } : {};
            this.lastPoint = [];
            this.makeState();
            this.touchFlag = false;
            this.canvas = document.getElementById('canvas');
            this.ctx = this.canvas.getContext('2d');
            this.lastPoint = [];
            this.arr = [];
            this.restPoint = [];
            this.createCircle();
            this.bindEvent();
        }
        H5lock.prototype.reset = function() {
            this.makeState();
            this.lastPoint = [];
            this.arr = [];
            this.restPoint = [];
            this.createCircle();
        }
        H5lock.prototype.bindEvent = function() {
            var self = this;
            this.canvas.addEventListener("touchstart", function (e) {
                e.preventDefault();// 某些android 的 touchmove不宜触发 所以增加此行代码
                 var po = self.getPosition(e);
                 for (var i = 0 ; i < self.arr.length ; i++) {
                    if (Math.abs(po.x - self.arr[i].x) < self.r && Math.abs(po.y - self.arr[i].y) < self.r) {
 
                        self.touchFlag = true;
                        self.drawPoint(self.arr[i].x,self.arr[i].y);
                        self.lastPoint.push(self.arr[i]);
                        self.restPoint.splice(i,1);
                        break;
                    }
                 }
             }, { passive: false });
             this.canvas.addEventListener("touchmove", function (e) {
                if (self.touchFlag) {
                    self.update(self.getPosition(e));
                    // console.log(self.lastPoint)
                }
             },  false );
             this.canvas.addEventListener("touchend", function (e) {
                 if (self.touchFlag) {
                     self.touchFlag = false;
                     self.storePass(self.lastPoint);
                     setTimeout(function(){
 
                        self.reset();
                    }, 
                    700);
                 }
 
 
             }, false);
             document.addEventListener('touchmove', function(e){
                e.preventDefault();
             },{ passive: false });
             document.getElementById('updatePassword').addEventListener('click', function(){
                 self.updatePassword();
              });
        }
})();